{% extends 'base.html' %}

{% block user_url %}
    {% url 'userprofile' username %}
{% endblock user_url %}

{% block user %}
    {{ username }}
{% endblock user %}

{% block login %}
    {#    <form method="POST" action="/logout/">#}
    {#        <input type="submit" class="btn btn-danger navbar-btn navbar-right" value="退出登录"/>#}
    {#        <input type="hidden" name="username" value={{ username }}>#}
    {#        {% csrf_token %}#}
    {#    </form>#}
    <input type="button" class="btn btn-danger navbar-btn navbar-right" onclick="logout()" value="退出登录"/>
{% endblock login %}

{% block room %}
    <div class="col-xs-3 col-sm-3 col-md-3">
        <div class="alert alert-success" role="alert" style="margin-top: 15px; margin-bottom: -15px">当前在线</div>
        <div id="online-list">
            <ul class="list-group" style="margin-top: 15px">
                <!-- Offline users will be dynamically added here -->
            </ul>
        </div>
        {#        <div id="room-list">#}
        {#            <ul class="list-group" style="margin-top: 15px">#}
        {#                {% for user in users_online %}#}
        {#                    {% if user.username == username %}#}
        {#                    {% else %}#}
        {#                        <li class="list-group-item">#}
        {#                            <a href="{% url 'friendprofile' username user.username %}"#}
        {#                               class="list-group-item">{{ user.username }}</a>#}
        {#                        </li>#}
        {#                    {% endif %}#}
        {#                {% endfor %}#}
        {#            </ul>#}
        {#        </div>#}
        <div>
            <div class="alert alert-success" role="alert" style="margin-top: 15px; margin-bottom: -15px">当前离线</div>
            <div id="offline-list">
                <ul class="list-group" style="margin-top: 15px">
                    <!-- Offline users will be dynamically added here -->
                </ul>
            </div>
            {#            <div id="room-list">#}
            {#                <ul class="list-group" style="margin-top: 15px">#}
            {#                    {% for user in users_offline %}#}
            {#                        {% if user.username == username %}#}
            {#                        {% else %}#}
            {#                            <li class="list-group-item">#}
            {#                                <a href="{% url 'friendprofile' username user.username %}"#}
            {#                                   class="list-group-item">{{ user.username }}</a>#}
            {#                            </li>#}
            {#                        {% endif %}#}
            {#                    {% endfor %}#}
            {#                </ul>#}
            {#            </div>#}
        </div>

    </div>

    <div class="col-xs-9 col-md-9 col-sm-9" style="margin-top: 15px; padding-right: 0px">
        <div id="room" style="height: 450px">
            <div class="panel panel-success">
                <div class="panel-heading">
                    聊天室：{{ roomname }}
                </div>
                <div class="panel-body" style="height: 350px; padding: 0px; ">
                        <textarea id="chat-log" style="height: 100%; width: 100%; border-color: #f5f5f5;">

                        </textarea>

                </div>
                <div class="panel-footer" style="padding: 0px">
                    <input id="chat-message-input" type="text"
                           style="width: 100%; height: 120px; border: #f5f5f5; border-top-color: #dff0d8; "/>
                    {#                    <div class="col-md-offset-9 col-md-3">#}
                    <div style="float: right">
                        <input id="chat-message-submit" class="btn btn-primary" type="button" value="发送"
                               style="margin-top: 10px;margin-bottom: 10px; "/>
                        <input id="chat-message-close" class="btn btn-danger" type="button" value="退出群聊"
                               style="margin-top: 10px;margin-bottom: 10px; "/>
                    </div>

                </div>

            </div>
        </div>
    </div>
{% endblock room %}


{% block script %}
    <script>
        var roomName = {{ room_name_json }};
        var userName = {{ user_name_json }};

        var chatSocket = new WebSocket(
            'ws://' + window.location.host +
            '/ws/chat/' + roomName + '/' + userName + '/');
        chatSocket.onmessage = function (e) {
            console.log(e)
            data = JSON.parse(e.data)
            {#var command = data['command'];#}
            if (data['command'] === 'update_users') {
                var usersOnline = data['users_online'];
                var usersOffline = data['users_offline'];
                console.log(usersOnline)
                console.log(usersOffline)

                // 更新在线用户列表
                // Update online user list
                var onlineList = document.getElementById('online-list');
                onlineList.innerHTML = '';
                usersOnline.forEach(function (user) {
                    if (user !== userName) {
                        var listItem = document.createElement('li');
                        listItem.classList.add('list-group-item');
                        var link = document.createElement('a');
                        link.textContent = user;
                        link.href = "/{{ username }}/friendprofile/" + user + "/";
                        {#link.href = "{% url 'friendprofile' username user %}";#}
                        link.classList.add('list-group-item');
                        listItem.appendChild(link);
                        onlineList.appendChild(listItem);
                    }

                });

                // Update offline user list
                var offlineList = document.getElementById('offline-list');
                offlineList.innerHTML = '';
                usersOffline.forEach(function (user) {
                    var listItem = document.createElement('li');
                    listItem.classList.add('list-group-item');
                    var link = document.createElement('a');
                    link.textContent = user;
                    link.href = "/{{ username }}/friendprofile/" + user + "/";
                    link.href = "{% url 'friendprofile' username user %}";
                    link.classList.add('list-group-item');
                    listItem.appendChild(link);
                    offlineList.appendChild(listItem);
                });
            } else {
                var text = data.message.text;
                document.querySelector('#chat-log').value += (text + '\n');
            }

        };
        chatSocket.onclose = function (e) {
            console.log("断开连接了")
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();
        document.querySelector('#chat-message-input').onkeyup = function (e) {
            if (e.keyCode === 13) {  // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function (e) {
            var messageInputDom = document.querySelector('#chat-message-input');
            var message = userName + ':\t' + messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message
            }));

            messageInputDom.value = '';
        };

        {#退出群聊#}
        document.querySelector('#chat-message-close').onclick = function (e) {
            chatSocket.close()
        };


        function logout() {
            // 先发送一个logout请求
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/logout/", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            // xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); // 添加 CSRF 令牌

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log('退出登录成功');
                    chatSocket.send(JSON.stringify({
                        'command': 'logout'
                    }));
                }
            };
            xhr.send(JSON.stringify({'username': userName}));
            // 用户退出登录时，自己发起一个关闭，还得发送一个退出大厅的消息类型

        }
        chatSocket.onclose = function (e) {
            // WebSocket 连接关闭时的处理逻辑
            console.log('WebSocket 连接已关闭');
            window.location.pathname = '';
            // 发送退出登录的 HTTP 请求
        };
    </script>
{% endblock script %}
